<route lang="json5" type="page">
  {
    layout: 'default',
    needLogin: true,
    style: {
      navigationBarTitleText: '预警提示',
      enablePullDownRefresh: true,
    },
  }
</route>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app'

// 搜索关键词
const keyword = ref('')

// 加载状态
const loading = ref(false)
const finished = ref(false)
const page = ref(1)

// 警报数据列表
const warningList = ref<any[]>([])

// 所有警报数据
const allWarningData = [
  {
    id: 1,
    type: 'water',
    typeName: '水量',
    value: -60.69,
    unit: '吨',
    meterName: '501水表',
    balance: -10.55,
    phone: '13888888888',
    isNegative: true,
  },
  {
    id: 2,
    type: 'electricity',
    typeName: '电量',
    value: 660.69,
    unit: '吨',
    meterName: '502电表',
    balance: 1.55,
    phone: '13999999999',
    isNegative: false,
  },
  {
    id: 3,
    type: 'electricity',
    typeName: '电量',
    value: 660.69,
    unit: '吨',
    meterName: '503电表',
    balance: 50.55,
    phone: '13777777777',
    isNegative: false,
  },
  {
    id: 4,
    type: 'water',
    typeName: '水量',
    value: 660.69,
    unit: '吨',
    meterName: '504水表',
    balance: 100.55,
    phone: '13666666666',
    isNegative: false,
  },
  {
    id: 5,
    type: 'water',
    typeName: '水量',
    value: 660.69,
    unit: '吨',
    meterName: '505水表',
    balance: 10.55,
    phone: '13555555555',
    isNegative: false,
  },
  {
    id: 6,
    type: 'electricity',
    typeName: '电量',
    value: -15.30,
    unit: '吨',
    meterName: '506电表',
    balance: -5.20,
    phone: '13444444444',
    isNegative: true,
  },
  {
    id: 7,
    type: 'water',
    typeName: '水量',
    value: 200.50,
    unit: '吨',
    meterName: '507水表',
    balance: 25.00,
    phone: '13333333333',
    isNegative: false,
  },
]

// 获取警报数据
function fetchWarningData(currentPage: number, searchKeyword: string) {
  return new Promise<any[]>((resolve) => {
    setTimeout(() => {
      let data = allWarningData
      if (searchKeyword) {
        data = data.filter(
          item => item.meterName.includes(searchKeyword) || item.typeName.includes(searchKeyword),
        )
      }
      const pageSize = 5
      const start = (currentPage - 1) * pageSize
      const end = currentPage * pageSize
      resolve(data.slice(start, end))
    }, 800)
  })
}

// 加载数据
async function loadData(isRefresh = false) {
  if (isRefresh) {
    page.value = 1
    finished.value = false
    warningList.value = []
  }

  if (loading.value || finished.value)
    return

  loading.value = true
  const newData = await fetchWarningData(page.value, keyword.value)
  loading.value = false
  uni.stopPullDownRefresh()

  if (newData.length) {
    warningList.value.push(...newData)
    page.value++
  }
  else {
    finished.value = true
  }
}

// 搜索功能
function onSearch() {
  loadData(true)
}

// 拨打电话
function makeCall(phone: string, meterName: string) {
  uni.showModal({
    title: '拨打电话',
    content: `确定要拨打 ${meterName} 的联系电话 ${phone} 吗？`,
    confirmText: '拨打',
    cancelText: '取消',
    success: (res) => {
      if (res.confirm) {
        uni.makePhoneCall({
          phoneNumber: phone,
          success: () => {
            console.log('拨打电话成功')
          },
          fail: () => {
            uni.showToast({
              title: '拨打电话失败',
              icon: 'error',
            })
          },
        })
      }
    },
  })
}

// 处理警报
function handleWarning(item: any) {
  uni.showToast({
    title: `处理 ${item.meterName} 的警报`,
    icon: 'none',
  })
}

// 获取状态标签类型
function getStatusType(item: any) {
  if (item.balance < 0)
    return 'danger'
  if (item.balance < 10)
    return 'warning'
  return 'success'
}

// 获取状态标签文本
function getStatusText(item: any) {
  if (item.balance < 0)
    return '余额不足'
  if (item.balance < 10)
    return '余额偏低'
  return '正常'
}

onMounted(() => {
  uni.showLoading({ title: '加载中...' })
  loadData().finally(() => {
    uni.hideLoading()
  })
})

onPullDownRefresh(() => {
  loadData(true)
})

onReachBottom(() => {
  loadData()
})
</script>

<template>
  <view class="min-h-screen">
    <!-- 搜索栏 -->
    <wd-search
      v-model="keyword"
      placeholder="请输入关键字"
      light
      hide-cancel
      @search="onSearch"
    />

    <wd-status-tip
      v-if="warningList.length === 0 && !loading"
      status="empty"
      title="暂无数据"
      description="暂无预警数据"
    />

    <!-- 警报列表 -->
    <view class="p-3">
      <wd-card
        v-for="item in warningList"
        :key="item.id"
        custom-class="!p-0 mb-3"
      >
        <view class="p-4">
          <!-- 表名称 -->
          <view class="mb-3 flex items-center justify-between text-sm">
            <text class="text-gray-600">
              {{ item.type === 'water' ? '水表名称' : '电表名称' }}
            </text>
            <text class="text-gray-800">
              {{ item.meterName }}
            </text>
          </view>

          <!-- 数值显示 -->
          <view class="mb-3 flex items-center justify-between">
            <text class="text-gray-600">
              {{ item.typeName }}
            </text>
            <view class="flex items-baseline">
              <text
                class="text-lg font-bold"
                :class="{
                  'text-red-500': item.isNegative,
                  'text-blue-500': item.type === 'water' && !item.isNegative,
                  'text-orange-500': item.type === 'electricity' && !item.isNegative,
                }"
              >
                {{ item.value }}
              </text>
              <text class="ml-1 text-sm font-bold">
                {{ item.unit }}
              </text>
            </view>
          </view>

          <!-- 表余额 -->
          <view class="mb-3 flex items-center justify-between text-sm">
            <text class="text-gray-600">
              表余额
            </text>
            <text
              class="text-gray-800"
              :class="{
                'text-red-500': item.balance < 0,
              }"
            >
              {{ item.balance }}
            </text>
          </view>

          <!-- 状态标签 -->
          <view class="flex items-center justify-between text-sm">
            <text class="text-gray-600">
              状态
            </text>
            <wd-tag
              :type="getStatusType(item)"
              size="small"
              round
            >
              {{ getStatusText(item) }}
            </wd-tag>
          </view>
        </view>

        <!-- 操作按钮区域 -->
        <view class="flex items-center justify-end border-t border-gray-100 p-3">
          <wd-button
            type="warning"
            size="small"
            custom-class="!ml-2"
            @click="makeCall(item.phone, item.meterName)"
          >
            拨打电话
          </wd-button>
        </view>
      </wd-card>

      <!-- 加载状态 -->
      <view class="py-4 text-center text-sm text-gray-500">
        <text v-if="loading">
          加载中...
        </text>
        <text v-else-if="finished">
          没有更多了
        </text>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
/* 可以在这里添加额外的样式 */
</style>
